﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.VFW;
using AForge.Video.FFMPEG;
using System.Drawing;
using System.Drawing.Imaging;

using System.IO;
namespace WebCam
{
    public class Camera
    {
        private VideoCaptureDevice vSource;
        Bitmap image;
        private VideoFileWriter writer;
        int _Width = 640;
        int _Height = 480;
        int _Frames = 25;
        bool _Record = false;
        #region CamSettings
        public int Exposure
        {
            set { vSource.SetCameraProperty(CameraControlProperty.Exposure, value, CameraControlFlags.Auto); }
            get
            {
                CameraControlFlags cFlag = CameraControlFlags.Auto;
                int valor;
                vSource.GetCameraProperty(CameraControlProperty.Exposure, out valor, out cFlag);
                return valor;
            }
        }
        public int Focus
        {
            set { vSource.SetCameraProperty(CameraControlProperty.Focus, value, CameraControlFlags.Auto); }
            get
            {
                CameraControlFlags cFlag = CameraControlFlags.Auto;
                int valor;
                vSource.GetCameraProperty(CameraControlProperty.Focus, out valor, out cFlag);
                return valor;
            }
        }
        public int Iris
        {
            set { vSource.SetCameraProperty(CameraControlProperty.Iris, value, CameraControlFlags.Auto); }
            get
            {
                CameraControlFlags cFlag = CameraControlFlags.Auto;
                int valor;
                vSource.GetCameraProperty(CameraControlProperty.Iris, out valor, out cFlag);
                return valor;
            }
        }
        public int Pan
        {
            set { vSource.SetCameraProperty(CameraControlProperty.Pan, value, CameraControlFlags.Auto); }
            get
            {
                CameraControlFlags cFlag = CameraControlFlags.Auto;
                int valor;
                vSource.GetCameraProperty(CameraControlProperty.Pan, out valor, out cFlag);
                return valor;
            }
        }
        public int Roll
        {
            set { vSource.SetCameraProperty(CameraControlProperty.Roll, value, CameraControlFlags.Auto); }
            get
            {
                CameraControlFlags cFlag = CameraControlFlags.Auto;
                int valor;
                vSource.GetCameraProperty(CameraControlProperty.Roll, out valor, out cFlag);
                return valor;
            }
        }
        public int Tilt
        {
            set { vSource.SetCameraProperty(CameraControlProperty.Tilt, value, CameraControlFlags.Auto); }
            get
            {
                CameraControlFlags cFlag = CameraControlFlags.Auto;
                int valor;
                vSource.GetCameraProperty(CameraControlProperty.Tilt, out valor, out cFlag);
                return valor;
            }
        }
        public int Zoom
        {
            set { vSource.SetCameraProperty(CameraControlProperty.Zoom, value, CameraControlFlags.Auto); }
            get
            {
                CameraControlFlags cFlag = CameraControlFlags.Auto;
                int valor;
                vSource.GetCameraProperty(CameraControlProperty.Zoom, out valor, out cFlag);
                return valor;
            }
        }
        #endregion
        public Camera(string device, int Width, int Height, int frames)
        {
            vSource = new VideoCaptureDevice(device);
            _Width = Width;
            _Height = Height;
            _Frames = frames;

        }
        void setCam(bool Record)
        {
            _Record = Record;
            foreach (VideoCapabilities vc in vSource.VideoCapabilities)
            {
                if (vc.FrameSize == new Size(_Width, _Height))
                {
                    vSource.VideoResolution = vc;
                    break;
                }
            }

            vSource.SetCameraProperty(CameraControlProperty.Exposure, 100, CameraControlFlags.Auto);
            vSource.NewFrame += new NewFrameEventHandler(FinalVideoSource_NewFrame);
            vSource.Start();

        }
        void FinalVideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            image = (Bitmap)eventArgs.Frame.Clone();
            //pictureBox1.Image = image;
            if (_Record)
            { writer.WriteVideoFrame(image); }

            if (NewFrame != null)
            {
                NewFrame(this, new NewFrameEventArgs((Bitmap)eventArgs.Frame));
            }
        }
        public void Record(string path)
        {
            vSource.SignalToStop();
            vSource.WaitForStop();
            writer = new VideoFileWriter();
            setCam(true);
            writer.Open(path, _Width, _Height, _Frames, VideoCodec.MPEG4, 128);
        }
        public void StopRecording()
        {
            vSource.SignalToStop();
            vSource.WaitForStop();
            writer.Close();
            _Record = false;
        }
        public void Preview()
        {
            vSource.SignalToStop();
            setCam(false);
        }
        public void CloseCam()
        {
            vSource.SignalToStop();
            if (_Record)
            {
                StopRecording();
            }
        }
        Image CompresedFrame(Image image, long Quality)
        {
            //byte[] bytFoto = null;
            using (MemoryStream m = new MemoryStream())
            {
                //comprimir aca
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality);
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;
                string mimeType = "image/jpeg";
                ImageCodecInfo codec = null;
                foreach (ImageCodecInfo ici in ImageCodecInfo.GetImageEncoders())
                {
                    if (ici.MimeType == mimeType)
                    {
                        codec = ici;
                    }
                }
                image.Save(m, codec, encoderParams);
                //bytFoto = m.ToArray();
            }
            //return Convert.ToBase64String(bytFoto);
            return image;
        }
        Image WaterMarkToImage(Image bmp, string watermark)
        {
            Graphics graphicsObject;
            int x, y;
            try
            {
                graphicsObject = Graphics.FromImage(bmp);
            }
            catch (Exception e)
            {
                Bitmap bmpNew = new Bitmap(bmp.Width, bmp.Height);
                graphicsObject = Graphics.FromImage(bmpNew);
                graphicsObject.DrawImage(bmp, new Rectangle(0, 0, bmpNew.Width, bmpNew.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);
                bmp = bmpNew;
            }
            int startsize = (bmp.Width / (watermark.Length + 5));//get the font size with respect to length of the string
            //x and y cordinates to draw a string
            x = 0;
            y = 0;//bmp.Height - (int)((decimal)bmp.Height * (decimal)0.1);

            System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(StringFormatFlags.NoWrap);
            graphicsObject.DrawString(watermark, new Font("Verdana", startsize, FontStyle.Bold), new SolidBrush(Color.FromArgb(209, 197, 84)), x, y, drawFormat);
            return (bmp);
        }


        public event EventHandler<NewFrameEventArgs> NewFrame;
    }
}
